package com.example.wan_android.viewmodel

import android.content.Context
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.wan_android.db.SearchHistoryData
import com.example.wan_android.db.SearchHistoryTable
import com.example.wan_android.http.bean.HotWordInfoData
import com.example.wan_android.http.code.HotWordRepository
import com.example.wan_android.ui.activity.SearchResultActivity
import com.example.wan_android.ui.activity.WebActivity
import kotlinx.coroutines.Dispatchers

import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SearchViewModel : BaseViewModel() {
    var context: Context? = null

    private val _hotWordListData = MutableLiveData<Result<List<HotWordInfoData>>>()
    val hotWordListData = _hotWordListData
    val repository = HotWordRepository()

    private val db by lazy {
        SearchHistoryData.getDatabase(context = this.context!!)
    }
    private val dao by lazy {
        db.searchHistoryDao()
    }
    val allSearchHistory: LiveData<List<SearchHistoryTable>> by lazy {
        dao.selectAll()
    }


    suspend fun addSearchHistory(searchWord: String) {
        withContext(Dispatchers.IO) {
            // 确保时间存储为Long而非String（实体类也需相应修改）
            dao.insert(
                SearchHistoryTable(
                    searchWord = searchWord,
                    searchTime = System.currentTimeMillis().toString()
                )
            )
        }
    }

    fun finish() {
        finishActivity()
    }

    fun clearSearchHistory() {
        viewModelScope.launch(Dispatchers.IO) {
            dao.deleteAll()
        }
    }

    fun deleteSearchHistory(id: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            dao.delete(id)
        }
    }

    init {
        getHotWords()
    }

    fun getHotWords() {
        viewModelScope.launch {
            _hotWordListData.value = repository.fetchHotWordInfoData()
        }
    }

    fun jumpSearchResult(word: String, name: String) {
        viewModelScope.launch(Dispatchers.Main) {
            // 异步添加历史记录
            allSearchHistory?.value?.forEach {
                if (it.searchWord == name) {
                    deleteSearchHistory(it.id)
                }
            }
            addSearchHistory(name)
            startActivity(Intent().apply {
                putExtra(SearchResultViewModel.searchWord, word)
                putExtra(SearchResultViewModel.title, name)
            }, targetClass = SearchResultActivity::class.java)
        }

    }

    fun openWeb(url: String, name: String) {
        viewModelScope.launch(Dispatchers.Main) {
            // 异步添加历史记录
            addSearchHistory(name)
            // 在协程中启动新Activity
            startActivity(Intent().apply {
                putExtra(WebViewModel.url, "https://www.baidu.com/s?wd=${url}")
            }, targetClass = WebActivity::class.java)
        }
    }
}